package com.ficv.tucanalmovil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.protocol.HTTP;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.ficv.tucanalmovil.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.location.Location;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.Settings.Secure;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.Toast;

public class JavaScriptInterface {
    Context mContext;
    WebView webView;
    Empresa empresa;
    
	private static final int HELLO_ID = 1;
    /** Instantiate the interface and set the context 
     * @param myWebView */
    JavaScriptInterface(Context c, WebView myWebView, Empresa e) {
        mContext = c;
        webView=myWebView;
        empresa=e;
    }

    /** Show a toast from the web page 
     * @throws ClassNotFoundException */
    
    public String get(String name)  {
    	
    	String result="";
    	
    	try {
			if (name.equalsIgnoreCase("desc"))
				result = empresa.getDescription();
			else if (name.equalsIgnoreCase("logo"))
				result = empresa.getImgUrl();
			else if (name.equalsIgnoreCase("width"))
				result = String.valueOf(((DisplayMessageActivity) mContext)
						.getWidth());
			else if (name.equalsIgnoreCase("width-avisos"))
				result = String.valueOf(((AvisoActivity) mContext)
						.getWindowManager().getDefaultDisplay().getWidth());
			else if (name.equalsIgnoreCase("avisos")) {
				StringBuffer sb = new StringBuffer();
				for (String s : empresa.getAvisos())
					sb.append("<p>" + s + ".</p>");
				result = sb.toString();
			}
		} catch (Throwable  e) {
			Log.e("ERROR", e.getCause() + ": " + e.getMessage());
		}
		return result;
    }
    
    public int doCmd(String toast) throws Exception {
    	
    	int resultado=1;
    	Log.e("CMD", toast);
    	
    	try {
	    	String[] result=toast.split("#");
	    	
	    	if (result[0].equals("llamada")) {
	        	Uri number = Uri.parse("tel:" + empresa.getPhone());
	        	Intent callIntent = new Intent(Intent.ACTION_CALL, number);
	        	callIntent(callIntent);
	
	    	} else if (result[0].equals("contact")) {
	
	    		Log.i("CMD", "contacto intent");
				String androidId=Secure.getString(mContext.getContentResolver(), Secure.ANDROID_ID);
			
				String url = Utils.getUrlContent(MainActivity.URL_BASE) + "contact?androidId=" + androidId + "&medio=" + URLEncoder.encode(result[1]);
	
				Utils.getUrlContent(url);
	//			URL msgurl = new URL(url);
	//			BufferedReader in = new BufferedReader(
	//			            new InputStreamReader(
	//			            msgurl.openStream()));
	//
	//			String inputLine;
	//			StringBuffer resultado = new StringBuffer();
	//			while ((inputLine = in.readLine()) != null) {
	//			    Log.i("CMD", inputLine);
	//			    resultado.append(inputLine);
	//			}    
	//			
	//			in.close();
	
	    	} else if (result[0].equals("web")) {
	        	Uri number = Uri.parse(empresa.getWeb());
	        	Intent callIntent = new Intent(Intent.ACTION_VIEW, number);
	        	callIntent(callIntent);
	
	    	} else if (result[0].equals("mail")) {
	    		Intent emailIntent = new Intent(Intent.ACTION_SEND);
	    		// The intent does not have a URI, so declare the "text/plain" MIME type
	    		emailIntent.setType(HTTP.PLAIN_TEXT_TYPE);
	    		emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {empresa.getEmail(),"francisco.isaac@gmail.com"}); // recipients
	    		emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Contacto");
	    		emailIntent.putExtra(Intent.EXTRA_TEXT, "Desearía información de sus productos");
	    		//emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://download/ResultsMenSummary.pdf"));
	    		
	    		callIntent(emailIntent);
	    	} else if (result[0].equals("tucanalmovil")) {
	    		Intent emailIntent = new Intent(Intent.ACTION_SEND);
	    		// The intent does not have a URI, so declare the "text/plain" MIME type
	    		emailIntent.setType(HTTP.PLAIN_TEXT_TYPE);
	    		emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"francisco.isaac@gmail.com"}); // recipients
	    		emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Contacto");
	    		emailIntent.putExtra(Intent.EXTRA_TEXT, "Desearía información sobre tucanalmovil");
	    		//emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://download/ResultsMenSummary.pdf"));
	    		
	    		callIntent(emailIntent);
	    	   		
	    	} else if (result[0].equals("mapa")) {
	    		Uri location = Uri.parse("geo:0,0?q=" + empresa.getLocation());
	    		// Uri location = Uri.parse("geo:37.422219,-122.08364?z=14"); // z param is zoom level
	    		Intent callIntent = new Intent(Intent.ACTION_VIEW, location);
	    		callIntent(callIntent);
	    	} else if (result[0].equals("close")) {
	    		((DisplayMessageActivity)mContext).finish();
	    	} else if (result[0].equals("contacto")) {
	    		  Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
	    		  ((DisplayMessageActivity)mContext).startActivityForResult(intentContact, ((DisplayMessageActivity)mContext).PICK_CONTACT);
	    	} else if (result[0].equals("xml")) {
	            
	//    		for(State s:getXML()) {
	//    			Toast.makeText(mContext, s.getName(), Toast.LENGTH_LONG).show();
	//    		}
	    			
	    		Toast.makeText(mContext, getEmpresa().toString(), Toast.LENGTH_LONG).show();
	    		
	    	} else if (result[0].equals("notify")) {
	    		String ns = Context.NOTIFICATION_SERVICE;
	    		NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(ns);
	    		
	    		int icon = R.drawable.ic_launcher;
	    		CharSequence tickerText = "Hello";
	    		long when = System.currentTimeMillis();
	
	    		Notification notification = new Notification(icon, tickerText, when);
	    		
	    		Context context = mContext.getApplicationContext();
	    		CharSequence contentTitle = "My gps notification";
	    		CharSequence contentText;
	    		Location location = ((DisplayMessageActivity)mContext).getLastLocation();
	    		if(location!=null) contentText = location.getLatitude() + ", " + location.getLongitude();
	    		else contentText="coords no disponibles";
	    		Intent notificationIntent = new Intent(mContext, DisplayMessageActivity.class);
	    		PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | PendingIntent.FLAG_ONE_SHOT);
	
	
	    		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
	    		
	    		
	
	
	    		mNotificationManager.notify(HELLO_ID, notification);
	    		
	    	} else {
	    		Intent i = new Intent();  
	    		 i.setAction(Intent.ACTION_MAIN);  
	    		 i.addCategory(Intent.CATEGORY_LAUNCHER);  
	    		  
	    		 String paquete = toast.substring(0,toast.lastIndexOf("."));
	    		 String clase = toast.substring(toast.lastIndexOf(".") + 1);
	    		 i.setFlags(  
	    		  Intent.FLAG_ACTIVITY_NEW_TASK |   
	    		  Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);  
	    		 i.setComponent(new ComponentName(  		  paquete,  clase));  
	    
	    		 mContext.startActivity(i);
	    	}
	    	
	        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();

	        
    	} catch(Throwable e) {
			Log.e("ERROR", e.getCause() + ": " + e.getMessage());
			resultado=-1;
    	}
    	
    	return resultado;
    }

	private void callIntent(Intent callIntent) {
		PackageManager packageManager = mContext.getPackageManager();
		List<ResolveInfo> activities = packageManager.queryIntentActivities(callIntent, 0);
		boolean isIntentSafe = activities.size() > 0;
		  
		// Start an activity if it's safe
		if (isIntentSafe) {
			mContext.startActivity(callIntent);
		}
	}
	
	protected List<State> getXML() 
	{
		try 
		{
			// The URL for making the GET request
			final String url = "http://192.168.2.102/states.xml";
			
			// Set the Accept header for "application/xml"
			HttpHeaders requestHeaders = new HttpHeaders();
			List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
			acceptableMediaTypes.add(MediaType.APPLICATION_XML);
			requestHeaders.setAccept(acceptableMediaTypes);
			
			// Populate the headers in an HttpEntity object to use for the request
			HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
			
			// Create a new RestTemplate instance
			RestTemplate restTemplate = new RestTemplate();
			
			// Perform the HTTP GET request
			ResponseEntity<StateList> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, StateList.class);
			
			// Return the list of states
			StateList stateList = responseEntity.getBody();

			return stateList.getStates();
		} 
		catch(Exception e) 
		{
			Log.e("TAG", e.getMessage(), e);
		} 
		
		return null;
	}
	
	protected Empresa getEmpresa() 
	{
		try 
		{
			// The URL for making the GET request
			final String url = "http://192.168.2.102/empresa.xml";
			
			// Set the Accept header for "application/xml"
			HttpHeaders requestHeaders = new HttpHeaders();
			List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
			acceptableMediaTypes.add(MediaType.APPLICATION_XML);
			requestHeaders.setAccept(acceptableMediaTypes);
			
			// Populate the headers in an HttpEntity object to use for the request
			HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
			
			// Create a new RestTemplate instance
			RestTemplate restTemplate = new RestTemplate();
			
			// Perform the HTTP GET request
			ResponseEntity<Empresa> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Empresa.class);
			
			// Return the list of states
			Empresa empresa = responseEntity.getBody();

			return empresa;
		} 
		catch(Throwable e) 
		{
			Log.e("ERROR", e.getCause() + ": " + e.getMessage());

		} 
		
		return null;
	}
}
